#!/usr/bin/env python
# encoding: utf-8
"""
snapshots.py

Created by Bud Gibson on 2010-06-17.
Copyright (c) Bud Gibson 2010. Released under the Artistic/GPL License.
"""
try:
  #from buzztracker.persistnet.db import get_db
  from buzztracker.persistnet.dbo import DataBase, transaction
  from buzztracker.conf import ZODB_CONF
except ImportError:
  import sys
  import os
  sys.path.append(os.path.join(os.path.dirname(__file__), '../..'))
  #from buzztracker.persistnet.db import get_db
  from buzztracker.persistnet.dbo import Database, transaction
  from buzztracker.conf import ZODB_CONF
import datetime

#db = get_db('rundb')
dbase = DataBase()
db = dbase.get_btree()

def store_snap(snap={'dateRun': datetime.datetime.now()},
              snapdb=db):
  """Stores a network snapshot in the configured database using the 
  timestamp as a key"""
  key = str(snap['dateRun']).replace(' ','-').replace(':','.')
  snapdb[key] = snap
  transaction.commit()
  dbase.pack()
  return key
  
def get_snap_index(index=-1,snapdb=db):
  """
  Gets a network snapshot from a certain position of the ordered snapshots 
  stored in the database.
  """
  cles = snapdb.keys()
  return snapdb[cles[index]]
  
def get_snap_key(key='',snapdb=db):
  """Gets a particular network snapshot based on the key used to save it"""
  return snapdb[key]
  
def get_snap(ki=None,snapdb=db):
  """
  gets a network snapshot by first trying index retrieval and then trying 
  key retrieval
  """
  try:
    return get_snap_index(ki,snapdb)
  except TypeError:
    return get_snap_key(ki,snapdb)
    
def get_object_list(snapdb=db):
  """returns a list of keys that can be used to access the current database"""
  return snapdb.keys()
  
def get_object_count(snapdb=db):
  """returns the number of objects in the database"""
  return len(snapdb.keys())

def main():
  print get_object_count()


if __name__ == '__main__':
  main()

